<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{.title}}</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f8f9fa;
            min-height: 100vh;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        header {
            text-align: center;
            margin-bottom: 40px;
            color: #333;
        }

        h1 {
            font-size: 2.2rem;
            margin-bottom: 10px;
            font-weight: 600;
            color: #2c3e50;
        }

        .actions {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 30px;
        }

        .btn {
            display: inline-block;
            padding: 10px 20px;
            background: #007bff;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            font-weight: 500;
            transition: background-color 0.2s ease;
            border: none;
            cursor: pointer;
            font-size: 14px;
        }

        .btn:hover {
            background: #0056b3;
        }

        .card {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            padding: 20px;
            margin-bottom: 20px;
            transition: border-color 0.2s ease;
        }

        .card:hover {
            border-color: #007bff;
        }

        .card h2 {
            color: #2c3e50;
            margin-bottom: 15px;
            font-size: 1.3rem;
            font-weight: 600;
            border-bottom: 1px solid #e9ecef;
            padding-bottom: 10px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            font-size: 14px;
            transition: border-color 0.2s ease;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #007bff;
        }

        .btn:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }

        .btn-secondary {
            background: #6c757d;
        }

        .btn-success {
            background: #28a745;
        }

        .btn-danger {
            background: #dc3545;
        }

        .progress-bar {
            width: 100%;
            height: 16px;
            background: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
            margin: 15px 0;
        }

        .progress-fill {
            height: 100%;
            background: #007bff;
            transition: width 0.3s ease;
            border-radius: 4px;
        }

        .status {
            padding: 8px 12px;
            border-radius: 4px;
            margin: 8px 0;
            font-weight: 500;
            font-size: 14px;
        }

        .status.pending {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }

        .status.processing {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .status.completed {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status.failed {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .groups-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .group-card {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            padding: 16px;
            transition: border-color 0.2s ease;
        }

        .group-card:hover {
            border-color: #007bff;
        }

        .group-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }

        .group-icon {
            font-size: 2rem;
            margin-right: 15px;
        }

        .group-info h3 {
            color: #4a5568;
            margin-bottom: 5px;
        }

        .group-info p {
            color: #718096;
            font-size: 0.9rem;
        }

        .group-stats {
            display: flex;
            justify-content: space-between;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #e2e8f0;
        }

        .stat {
            text-align: center;
        }

        .stat-value {
            font-size: 1.2rem;
            font-weight: 600;
            color: #4a5568;
        }

        .stat-label {
            font-size: 0.8rem;
            color: #718096;
        }

        .loading {
            text-align: center;
            padding: 40px;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .hidden {
            display: none;
        }

        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            margin: 10px 0;
            border: 1px solid #f5c6cb;
        }

        .success {
            background: #d4edda;
            color: #155724;
            padding: 15px;
            border-radius: 8px;
            margin: 10px 0;
            border: 1px solid #c3e6cb;
        }

        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #e9ecef;
            background: white;
            border-radius: 6px 6px 0 0;
            overflow: hidden;
        }

        .tab {
            padding: 12px 20px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.2s ease;
            background: #f8f9fa;
            color: #6c757d;
            font-weight: 500;
        }

        .tab.active {
            border-bottom-color: #007bff;
            color: #007bff;
            background: white;
            font-weight: 600;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .algorithm-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .algorithm-card {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            padding: 16px;
            text-align: center;
            transition: border-color 0.2s ease;
            cursor: pointer;
        }

        .algorithm-card:hover {
            border-color: #007bff;
        }

        .algorithm-card.selected {
            border-color: #007bff;
            background: #f8f9fa;
        }

        .algorithm-icon {
            font-size: 3rem;
            margin-bottom: 15px;
        }

        .algorithm-name {
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 10px;
            color: #4a5568;
        }

        .algorithm-desc {
            color: #718096;
            font-size: 0.9rem;
        }

        /* 分组展开/收起样式 */
        .group-header {
            cursor: pointer;
            user-select: none;
        }

        .group-toggle {
            margin-left: auto;
            padding: 10px;
        }

        .toggle-icon {
            font-size: 1.2rem;
            color: #667eea;
            transition: transform 0.3s ease;
        }

        .group-urls {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #e2e8f0;
        }

        .urls-header {
            margin-bottom: 15px;
        }

        .urls-header h4 {
            color: #4a5568;
            font-size: 1.1rem;
            margin: 0;
        }

        .urls-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .url-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px;
            margin-bottom: 8px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e9ecef;
            transition: all 0.3s ease;
        }

        .url-item:hover {
            background: #e9ecef;
            border-color: #667eea;
        }

        .url-info {
            flex: 1;
            margin-right: 15px;
        }

        .url-title {
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 4px;
            word-break: break-word;
        }

        .url-link {
            color: #667eea;
            font-size: 0.9rem;
            margin-bottom: 6px;
            word-break: break-all;
        }

        .url-meta {
            display: flex;
            gap: 15px;
            font-size: 0.8rem;
            color: #718096;
        }

        .visit-count {
            background: #e6f3ff;
            color: #0066cc;
            padding: 2px 6px;
            border-radius: 4px;
        }

        .last-visit {
            color: #718096;
        }

        .url-actions {
            flex-shrink: 0;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 0.8rem;
            border-radius: 4px;
        }

        .no-urls {
            text-align: center;
            color: #718096;
            padding: 20px;
            font-style: italic;
        }

        .urls-loading {
            text-align: center;
            color: #718096;
            padding: 20px;
        }

        .error {
            color: #e53e3e;
            text-align: center;
            padding: 20px;
        }

        /* 版本分组样式 */
        .version-card {
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            background: #f8f9fa;
            overflow: hidden;
        }

        .version-groups {
            background: white;
            border-top: 1px solid #e2e8f0;
            padding: 20px;
        }

        .no-groups {
            text-align: center;
            color: #718096;
            padding: 20px;
            font-style: italic;
        }

        @media (max-width: 768px) {
            .actions {
                flex-direction: column;
                align-items: center;
                gap: 10px;
            }
            
            h1 {
                font-size: 1.8rem;
            }
            
            .card {
                padding: 15px;
            }
            
            .tabs {
                flex-wrap: wrap;
            }
            
            .tab {
                flex: 1;
                min-width: 120px;
                text-align: center;
            }
            
            .groups-container {
                grid-template-columns: 1fr;
            }
            
            .algorithm-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>🤖 AI智能分组</h1>
        </header>

        <!-- 操作按钮 -->
        <div class="actions">
            <a href="/" class="btn">🏠 返回首页</a>
            <a href="/import" class="btn">导入浏览器数据</a>
            <a href="/test-extension" class="btn">🧪 扩展测试</a>
            <a href="/stat" class="btn">📊 统计数据</a>
        </div>

        <div class="tabs">
            <div class="tab active" onclick="switchTab('create')">创建分组</div>
            <div class="tab" onclick="switchTab('manage')">管理分组</div>
            <div class="tab" onclick="switchTab('analyze')">模式分析</div>
            <div class="tab" onclick="switchTab('test')">算法测试</div>
        </div>

        <!-- 创建分组标签页 -->
        <div id="create" class="tab-content active">
            <div class="card">
                <h2>创建新的AI分组版本</h2>
                <form id="createVersionForm">
                    <div class="form-group">
                        <label for="versionName">版本名称</label>
                        <input type="text" id="versionName" name="name" placeholder="例如：2024年1月分组" required>
                    </div>
                    <div class="form-group">
                        <label for="versionDescription">版本描述</label>
                        <textarea id="versionDescription" name="description" placeholder="描述这个分组版本的特点..."></textarea>
                    </div>
                    <div class="form-group">
                        <label for="algorithmType">分组算法</label>
                        <select id="algorithmType" name="algorithmType" required>
                            <option value="frequency">频率分析</option>
                            <option value="time_pattern">时间模式</option>
                            <option value="content_similarity">内容相似性</option>
                            <option value="ai_enhanced">AI增强</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="userPrompt">用户偏好（可选）</label>
                        <textarea id="userPrompt" name="userPrompt" placeholder="描述你希望如何分组网站..."></textarea>
                    </div>
                    <button type="submit" class="btn">创建版本</button>
                </form>
            </div>

            <div class="card" id="versionCard" style="display: none;">
                <h2>分组任务</h2>
                <div id="taskStatus"></div>
                <div id="progressContainer" style="display: none;">
                    <div class="progress-bar">
                        <div class="progress-fill" id="progressFill" style="width: 0%"></div>
                    </div>
                    <div id="progressText">准备中...</div>
                </div>
                <button id="startGroupingBtn" class="btn" style="display: none;">开始分组</button>
            </div>
        </div>

        <!-- 管理分组标签页 -->
        <div id="manage" class="tab-content">
            <div class="card">
                <h2>分组版本列表</h2>
                <div id="versionsList">
                    <div class="loading">
                        <div class="spinner"></div>
                        <p>加载中...</p>
                    </div>
                </div>
            </div>

            <div class="card" id="groupsCard" style="display: none;">
                <h2>分组结果</h2>
                <div id="groupsContainer" class="groups-container"></div>
            </div>
        </div>

        <!-- 模式分析标签页 -->
        <div id="analyze" class="tab-content">
            <div class="card">
                <h2>浏览模式分析</h2>
                <p>分析你的浏览习惯，发现访问模式和兴趣偏好</p>
                <button id="analyzeBtn" class="btn">开始分析</button>
                <div id="analysisResult" style="display: none;"></div>
            </div>
        </div>

        <!-- 算法测试标签页 -->
        <div id="test" class="tab-content">
            <div class="card">
                <h2>算法测试</h2>
                <p>测试不同分组算法的效果</p>
                <div class="form-group">
                    <label for="testAlgorithm">选择算法</label>
                    <select id="testAlgorithm" name="algorithmType">
                        <option value="frequency">频率分析</option>
                        <option value="time_pattern">时间模式</option>
                        <option value="content_similarity">内容相似性</option>
                        <option value="ai_enhanced">AI增强</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="testSampleSize">样本大小</label>
                    <input type="number" id="testSampleSize" name="sampleSize" value="50" min="10" max="200">
                </div>
                <button id="testBtn" class="btn">开始测试</button>
                <div id="testResult" style="display: none;"></div>
            </div>
        </div>
    </div>

    <script>
        let currentVersion = null;
        let taskInterval = null;

        // 切换标签页
        function switchTab(tabName) {
            // 隐藏所有标签页内容
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 移除所有标签的active类
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的标签页
            document.getElementById(tabName).classList.add('active');
            event.target.classList.add('active');
            
            // 根据标签页加载数据
            if (tabName === 'manage') {
                loadVersions();
            }
        }

         // 创建版本表单提交
         document.getElementById('createVersionForm').addEventListener('submit', async (e) => {
             e.preventDefault();
             
             const formData = new FormData(e.target);
             const data = {
                 name: formData.get('name'),
                 description: formData.get('description'),
                 config: {
                     algorithmType: formData.get('algorithmType'),
                     userPrompt: formData.get('userPrompt'),
                     minGroupSize: 3,
                     maxGroupSize: 20,
                     similarityThreshold: 0.3
                 }
             };

             try {
                 const response = await fetch('/api/ai-grouping/versions', {
                     method: 'POST',
                     headers: {
                         'Content-Type': 'application/json',
                     },
                     body: JSON.stringify(data)
                 });

                 const result = await response.json();
                 
                 if (result.code === 200) {
                     currentVersion = result.data;
                     document.getElementById('versionCard').style.display = 'block';
                     document.getElementById('startGroupingBtn').style.display = 'block';
                     showMessage('版本创建成功！', 'success');
                     
                     // 创建分组任务
                     await createGroupingTask(currentVersion.id);
                 } else {
                     showMessage('创建失败：' + result.message, 'error');
                 }
             } catch (error) {
                 showMessage('请求失败：' + error.message, 'error');
             }
         });

         // 开始分组
         document.getElementById('startGroupingBtn').addEventListener('click', async () => {
             if (!currentVersion) return;

             try {
                 // 更新任务状态为处理中
                 const response = await fetch('/api/ai-grouping/tasks', {
                     method: 'POST',
                     headers: {
                         'Content-Type': 'application/json',
                     },
                     body: JSON.stringify({
                         versionId: parseInt(currentVersion.id),
                         status: 'processing',
                         progress: 0,
                         message: '开始分组处理...'
                     })
                 });

                 const result = await response.json();
                 
                 if (result.code === 200) {
                     document.getElementById('progressContainer').style.display = 'block';
                     document.getElementById('startGroupingBtn').style.display = 'none';
                     
                     // 执行真实分组过程
                     executeGroupingProcess(currentVersion.id);
                     showMessage('分组任务已开始！', 'success');
                 } else {
                     showMessage('启动失败：' + result.message, 'error');
                 }
             } catch (error) {
                 showMessage('请求失败：' + error.message, 'error');
             }
         });

         // 轮询任务状态
         function startTaskPolling(versionId) {
             taskInterval = setInterval(async () => {
                 try {
                     const response = await fetch('/api/ai-grouping/tasks/' + versionId);
                     const result = await response.json();
                     
                     if (result.code === 200) {
                         const task = result.data;
                         updateTaskStatus(task);
                         
                         if (task.status === 'completed' || task.status === 'failed') {
                             clearInterval(taskInterval);
                             if (task.status === 'completed') {
                                 loadGroups(versionId);
                                 showMessage('分组完成！', 'success');
                             } else {
                                 showMessage('分组失败：' + (task.message || '未知错误'), 'error');
                             }
                         }
                     }
                 } catch (error) {
                     console.error('轮询任务状态失败：', error);
                 }
             }, 2000);
         }

        // 更新任务状态
        function updateTaskStatus(task) {
            const statusDiv = document.getElementById('taskStatus');
            const progressFill = document.getElementById('progressFill');
            const progressText = document.getElementById('progressText');
            
            statusDiv.innerHTML = '<div class="status ' + task.status + '">状态：' + getStatusText(task.status) + '</div>';
            progressFill.style.width = task.progress + '%';
            progressText.textContent = task.progress + '% - ' + (task.message || '处理中...');
        }

        // 获取状态文本
        function getStatusText(status) {
            const statusMap = {
                'pending': '等待中',
                'processing': '处理中',
                'completed': '已完成',
                'failed': '失败'
            };
            return statusMap[status] || status;
        }

         // 加载分组结果
         async function loadGroups(versionId) {
             try {
                 const response = await fetch('/api/ai-grouping/groups?versionId=' + versionId);
                 const result = await response.json();
                 
                 if (result.code === 200) {
                     displayGroups(result.data);
                     document.getElementById('groupsCard').style.display = 'block';
                 } else {
                     showMessage('加载分组失败：' + result.message, 'error');
                 }
             } catch (error) {
                 console.error('加载分组失败：', error);
                 showMessage('加载分组失败：' + error.message, 'error');
             }
         }

        // 显示分组结果
        function displayGroups(groups) {
            const container = document.getElementById('groupsContainer');
            
            if (groups.length === 0) {
                container.innerHTML = '<p>暂无分组结果</p>';
                return;
            }

            // 计算统计信息
            const totalURLs = groups.reduce((sum, group) => sum + (group.urlCount || 0), 0);
            const avgConfidence = groups.length > 0 ? 
                groups.reduce((sum, group) => sum + (group.confidence || 0), 0) / groups.length : 0;

            container.innerHTML = 
                '<h3>分组结果</h3>' +
                '<div class="card">' +
                    '<h4>统计信息</h4>' +
                    '<p>总URL数：' + totalURLs + '</p>' +
                    '<p>已分组：' + totalURLs + '</p>' +
                    '<p>未分组：0</p>' +
                    '<p>分组数量：' + groups.length + '</p>' +
                    '<p>平均置信度：' + Math.round(avgConfidence * 100) + '%</p>' +
                    '<p>处理时间：' + new Date().toLocaleString('zh-CN') + '</p>' +
                '</div>' +
                '<div class="groups-container">' +
                    groups.map((group, index) => 
                        '<div class="group-card" data-group-id="' + group.id + '">' +
                            '<div class="group-header" onclick="toggleGroup(' + index + ')">' +
                                '<div class="group-icon">' + (group.icon || '📁') + '</div>' +
                                '<div class="group-info">' +
                                    '<h3>' + group.name + '</h3>' +
                                    '<p>' + (group.description || '无描述') + '</p>' +
                                '</div>' +
                                '<div class="group-toggle">' +
                                    '<span class="toggle-icon">▼</span>' +
                                '</div>' +
                            '</div>' +
                            '<div class="group-stats">' +
                                '<div class="stat">' +
                                    '<div class="stat-value">' + (group.urlCount || 0) + '</div>' +
                                    '<div class="stat-label">网站数量</div>' +
                                '</div>' +
                                '<div class="stat">' +
                                    '<div class="stat-value">' + Math.round((group.confidence || 0) * 100) + '%</div>' +
                                    '<div class="stat-label">置信度</div>' +
                                '</div>' +
                            '</div>' +
                            '<div class="group-urls" id="group-urls-' + index + '" style="display: none;">' +
                                '<div class="urls-loading">加载中...</div>' +
                            '</div>' +
                        '</div>'
                    ).join('') +
                '</div>';

            // 为每个分组加载URL列表
            groups.forEach((group, index) => {
                loadGroupURLs(group.id, index);
            });
        }

        // 加载版本列表
        async function loadVersions() {
            try {
                const response = await fetch('/api/ai-grouping/versions');
                const result = await response.json();
                
                if (result.code === 200) {
                    displayVersions(result.data);
                }
            } catch (error) {
                console.error('加载版本失败：', error);
            }
        }

         // 显示版本列表
         function displayVersions(versions) {
             const container = document.getElementById('versionsList');
             
             if (versions.length === 0) {
                 container.innerHTML = '<p>暂无分组版本</p>';
                 return;
             }

             container.innerHTML = versions.map(version => 
                 '<div class="version-card" data-version-id="' + version.id + '" style="margin-bottom: 20px;">' +
                     '<div class="card" style="margin-bottom: 0;">' +
                         '<h3>' + version.name + '</h3>' +
                         '<p>' + (version.description || '无描述') + '</p>' +
                         '<div class="status ' + version.status + '">状态：' + getStatusText(version.status) + '</div>' +
                         '<div style="margin-top: 15px;">' +
                             '<button class="btn btn-secondary" onclick="viewVersion(\'' + version.id + '\')">查看详情</button>' +
                             (version.status === 'completed' ? '<button class="btn" onclick="toggleVersionGroups(\'' + version.id + '\')">查看分组</button>' : '') +
                             (version.status === 'completed' ? '<button class="btn btn-success" onclick="useGrouping(\'' + version.id + '\')" style="margin-left: 10px;">使用分组</button>' : '') +
                             '<button class="btn btn-danger" onclick="deleteVersion(\'' + version.id + '\')" style="margin-left: 10px;">删除</button>' +
                         '</div>' +
                     '</div>' +
                     '<div class="version-groups" id="version-groups-' + version.id + '" style="display: none; margin-top: 15px;">' +
                         '<div class="loading">加载中...</div>' +
                     '</div>' +
                 '</div>'
             ).join('');
         }

         // 查看版本详情
         function viewVersion(versionId) {
             // 这里可以添加查看版本详情的逻辑
             console.log('查看版本：', versionId);
         }

         // 切换版本分组显示
         async function toggleVersionGroups(versionId) {
             const groupsContainer = document.getElementById('version-groups-' + versionId);
             const button = event.target;
             
             if (groupsContainer.style.display === 'none') {
                 // 展开分组
                 groupsContainer.style.display = 'block';
                 button.textContent = '收起分组';
                 
                 // 加载分组数据
                 await loadVersionGroups(versionId);
             } else {
                 // 收起分组
                 groupsContainer.style.display = 'none';
                 button.textContent = '查看分组';
             }
         }

         // 加载版本分组数据
         async function loadVersionGroups(versionId) {
             try {
                 const response = await fetch('/api/ai-grouping/groups?versionId=' + versionId);
                 const result = await response.json();
                 
                 const groupsContainer = document.getElementById('version-groups-' + versionId);
                 
                 if (result.code === 200 && result.data.length > 0) {
                     groupsContainer.innerHTML = displayVersionGroups(result.data, versionId);
                 } else {
                     groupsContainer.innerHTML = '<div class="no-groups">该版本暂无分组结果</div>';
                 }
             } catch (error) {
                 console.error('加载版本分组失败：', error);
                 const groupsContainer = document.getElementById('version-groups-' + versionId);
                 groupsContainer.innerHTML = '<div class="error">加载失败：' + error.message + '</div>';
             }
         }

         // 显示版本分组结果
         function displayVersionGroups(groups, versionId) {
             const html = groups.map((group, index) => 
                 '<div class="group-card" data-group-id="' + group.id + '">' +
                     '<div class="group-header" onclick="toggleGroup(\'' + versionId + '-' + index + '\')">' +
                         '<div class="group-icon">' + (group.icon || '📁') + '</div>' +
                         '<div class="group-info">' +
                             '<h3>' + group.name + '</h3>' +
                             '<p>' + (group.description || '无描述') + '</p>' +
                         '</div>' +
                         '<div class="group-toggle">' +
                             '<span class="toggle-icon">▼</span>' +
                         '</div>' +
                     '</div>' +
                     '<div class="group-stats">' +
                         '<div class="stat">' +
                             '<div class="stat-value">' + (group.urlCount || 0) + '</div>' +
                             '<div class="stat-label">网站数量</div>' +
                         '</div>' +
                         '<div class="stat">' +
                             '<div class="stat-value">' + Math.round((group.confidence || 0) * 100) + '%</div>' +
                             '<div class="stat-label">置信度</div>' +
                         '</div>' +
                     '</div>' +
                     '<div class="group-urls" id="group-urls-' + versionId + '-' + index + '" style="display: none;">' +
                         '<div class="urls-loading">加载中...</div>' +
                     '</div>' +
                 '</div>'
             ).join('');
             
             // 为每个分组加载URL列表
             setTimeout(() => {
                 groups.forEach((group, index) => {
                     loadGroupURLs(group.id, versionId + '-' + index);
                 });
             }, 100);
             
             return html;
         }

         // 使用分组
         async function useGrouping(versionId) {
             if (!confirm('确定要使用这个分组版本吗？这将更新个人导航页面的显示内容。')) {
                 return;
             }

             try {
                 const response = await fetch('/api/ai-grouping/use-grouping', {
                     method: 'POST',
                     headers: {
                         'Content-Type': 'application/json',
                     },
                     body: JSON.stringify({
                         versionId: parseInt(versionId)
                     })
                 });

                 const result = await response.json();
                 
                 if (result.code === 200) {
                     showMessage('分组已应用到个人导航页面！', 'success');
                     
                     // 可选：跳转到个人导航页面查看效果
                     if (confirm('是否要跳转到个人导航页面查看效果？')) {
                         window.open('/', '_blank');
                     }
                 } else {
                     showMessage('应用分组失败：' + result.message, 'error');
                 }
             } catch (error) {
                 showMessage('请求失败：' + error.message, 'error');
             }
         }

         // 删除版本
         async function deleteVersion(versionId) {
             if (!confirm('确定要删除这个版本吗？此操作不可撤销。')) {
                 return;
             }

             try {
                 const response = await fetch('/api/ai-grouping/versions/' + versionId, {
                     method: 'DELETE'
                 });

                 const result = await response.json();
                 
                 if (result.code === 200) {
                     showMessage('版本删除成功！', 'success');
                     loadVersions(); // 重新加载版本列表
                 } else {
                     showMessage('删除失败：' + result.message, 'error');
                 }
             } catch (error) {
                 showMessage('请求失败：' + error.message, 'error');
             }
         }

         // 创建分组任务
         async function createGroupingTask(versionId) {
             try {
                 const response = await fetch('/api/ai-grouping/tasks', {
                     method: 'POST',
                     headers: {
                         'Content-Type': 'application/json',
                     },
                     body: JSON.stringify({
                         versionId: parseInt(versionId),
                         status: 'pending',
                         progress: 0,
                         message: '任务已创建，等待开始...'
                     })
                 });

                 const result = await response.json();
                 
                 if (result.code === 200) {
                     console.log('分组任务创建成功');
                 } else {
                     console.error('创建分组任务失败：', result.message);
                 }
             } catch (error) {
                 console.error('创建分组任务失败：', error);
             }
         }

         // 执行真实的分组过程
         async function executeGroupingProcess(versionId) {
             try {
                 // 更新任务状态为处理中
                 updateTaskStatus({
                     status: 'processing',
                     progress: 10,
                     message: '正在分析浏览数据...'
                 });

                 // 调用后端执行分组
                 const response = await fetch('/api/ai-grouping/execute', {
                     method: 'POST',
                     headers: {
                         'Content-Type': 'application/json',
                     },
                     body: JSON.stringify({
                         versionId: parseInt(versionId)
                     })
                 });

                 const result = await response.json();
                 
                 if (result.code === 200) {
                     // 更新任务状态为完成
                     updateTaskStatus({
                         status: 'completed',
                         progress: 100,
                         message: '分组完成！'
                     });

                     // 分组完成后加载结果
                     await loadGroups(versionId);
                     showMessage('分组完成！', 'success');
                 } else {
                     // 更新任务状态为失败
                     updateTaskStatus({
                         status: 'failed',
                         progress: 0,
                         message: '分组失败：' + result.message
                     });
                     showMessage('分组失败：' + result.message, 'error');
                 }
             } catch (error) {
                 console.error('执行分组失败：', error);
                 // 更新任务状态为失败
                 updateTaskStatus({
                     status: 'failed',
                     progress: 0,
                     message: '分组失败：' + error.message
                 });
                 showMessage('分组失败：' + error.message, 'error');
             }
         }

         // 分析浏览模式
         document.getElementById('analyzeBtn').addEventListener('click', async () => {
             try {
                 const response = await fetch('/api/ai-grouping/patterns');
                 const result = await response.json();
                 
                 if (result.code === 200) {
                     displayAnalysisResult(result.data);
                     showMessage('分析完成！', 'success');
                 } else {
                     showMessage('分析失败：' + result.message, 'error');
                 }
             } catch (error) {
                 showMessage('请求失败：' + error.message, 'error');
             }
         });

        // 显示分析结果
        function displayAnalysisResult(data) {
            const container = document.getElementById('analysisResult');
            container.style.display = 'block';
            
            container.innerHTML = 
                '<h3>分析结果</h3>' +
                '<div class="card">' +
                    '<h4>兴趣领域</h4>' +
                    '<p>' + (data.interests ? data.interests.join(', ') : '暂无数据') + '</p>' +
                '</div>' +
                '<div class="card">' +
                    '<h4>时间偏好</h4>' +
                    '<p>' + JSON.stringify(data.timePreferences, null, 2) + '</p>' +
                '</div>' +
                '<div class="card">' +
                    '<h4>使用习惯</h4>' +
                    '<p>' + JSON.stringify(data.usageHabits, null, 2) + '</p>' +
                '</div>';
        }

         // 测试算法
         document.getElementById('testBtn').addEventListener('click', async () => {
             const algorithmType = document.getElementById('testAlgorithm').value;
             const sampleSize = parseInt(document.getElementById('testSampleSize').value);
             
             try {
                 const response = await fetch('/api/ai-grouping/test', {
                     method: 'POST',
                     headers: {
                         'Content-Type': 'application/json',
                     },
                     body: JSON.stringify({
                         algorithmType: algorithmType,
                         sampleSize: sampleSize
                     })
                 });
                 
                 const result = await response.json();
                 
                 if (result.code === 200) {
                     displayTestResult(result.data);
                     showMessage('算法测试完成！', 'success');
                 } else {
                     showMessage('测试失败：' + result.message, 'error');
                 }
             } catch (error) {
                 showMessage('请求失败：' + error.message, 'error');
             }
         });

        // 显示测试结果
        function displayTestResult(data) {
            const container = document.getElementById('testResult');
            container.style.display = 'block';
            
            container.innerHTML = 
                '<h3>测试结果 - ' + (data.algorithmType || '未知算法') + '</h3>' +
                '<div class="card">' +
                    '<h4>统计信息</h4>' +
                    '<p>总URL数：' + (data.statistics.totalURLs || 0) + '</p>' +
                    '<p>已分组：' + (data.statistics.groupedURLs || 0) + '</p>' +
                    '<p>未分组：' + (data.statistics.unassignedURLs || 0) + '</p>' +
                    '<p>分组数量：' + (data.statistics.groupCount || 0) + '</p>' +
                    '<p>平均置信度：' + Math.round((data.statistics.avgConfidence || 0) * 100) + '%</p>' +
                    '<p>处理时间：' + (data.statistics.processingTime || 0) + 'ms</p>' +
                    '<p>测试时间：' + (data.testTime || '未知') + '</p>' +
                '</div>' +
                '<div class="card" style="margin-top: 20px;">' +
                    '<h4>操作</h4>' +
                    '<button id="useTestResultBtn" class="btn" onclick="useTestResult()">' +
                        '✅ 使用此结果创建分组' +
                    '</button>' +
                    '<p style="margin-top: 10px; color: #6c757d; font-size: 14px;">' +
                        '点击按钮将使用当前测试结果创建一个新的分组版本' +
                    '</p>' +
                '</div>' +
                '<div class="groups-container">' +
                    (data.groups || []).map((group, index) => 
                        '<div class="group-card" data-group-id="' + group.id + '">' +
                            '<div class="group-header" onclick="toggleTestGroup(' + index + ')">' +
                                '<div class="group-icon">' + (group.icon || '📁') + '</div>' +
                                '<div class="group-info">' +
                                    '<h3>' + group.name + '</h3>' +
                                    '<p>' + (group.description || '无描述') + '</p>' +
                                '</div>' +
                                '<div class="group-toggle">' +
                                    '<span class="toggle-icon">▼</span>' +
                                '</div>' +
                            '</div>' +
                            '<div class="group-stats">' +
                                '<div class="stat">' +
                                    '<div class="stat-value">' + (group.urlCount || 0) + '</div>' +
                                    '<div class="stat-label">网站数量</div>' +
                                '</div>' +
                                '<div class="stat">' +
                                    '<div class="stat-value">' + Math.round((group.confidence || 0) * 100) + '%</div>' +
                                    '<div class="stat-label">置信度</div>' +
                                '</div>' +
                            '</div>' +
                            '<div class="group-urls" id="test-group-urls-' + index + '" style="display: none;">' +
                                '<div class="urls-loading">加载中...</div>' +
                            '</div>' +
                        '</div>'
                    ).join('') +
                '</div>';
            
            // 保存测试结果数据供后续使用
            window.currentTestResult = data;
            
            // 为每个分组加载URL列表
            (data.groups || []).forEach((group, index) => {
                loadTestGroupURLs(group, index);
            });
        }

        // 使用测试结果创建分组
        async function useTestResult() {
            if (!window.currentTestResult) {
                showMessage('没有可用的测试结果', 'error');
                return;
            }

            const testData = window.currentTestResult;
            
            // 生成版本名称
            const versionName = '测试结果分组 - ' + (testData.algorithmType || '未知算法') + ' - ' + new Date().toLocaleString('zh-CN');
            
            try {
                // 创建新版本
                const createResponse = await fetch('/api/ai-grouping/versions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        name: versionName,
                        description: '基于算法测试结果创建的分组版本',
                        algorithmType: testData.algorithmType || 'domain_based'
                    })
                });

                const createResult = await createResponse.json();
                
                if (createResult.code === 200) {
                    const versionId = createResult.data.id;
                    
                    // 使用测试结果创建分组
                    const useResponse = await fetch('/api/ai-grouping/use-grouping', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            versionId: versionId,
                            testResult: testData
                        })
                    });

                    const useResult = await useResponse.json();
                    
                    if (useResult.code === 200) {
                        showMessage('成功使用测试结果创建分组！', 'success');
                        
                        // 切换到管理分组标签页并刷新列表
                        switchTab('manage');
                        await loadVersions();
                        
                        // 自动选择新创建的版本
                        setTimeout(() => {
                            const versionElement = document.querySelector(`[data-version-id="${versionId}"]`);
                            if (versionElement) {
                                versionElement.click();
                            }
                        }, 500);
                    } else {
                        showMessage('使用测试结果失败：' + useResult.message, 'error');
                    }
                } else {
                    showMessage('创建版本失败：' + createResult.message, 'error');
                }
            } catch (error) {
                showMessage('请求失败：' + error.message, 'error');
            }
        }

        // 切换分组展开/收起
        function toggleGroup(index) {
             const urlsContainer = document.getElementById('group-urls-' + index);
             const toggleIcon = document.querySelector(`#group-urls-${index}`).parentElement.querySelector('.toggle-icon');
             
             if (urlsContainer.style.display === 'none') {
                 urlsContainer.style.display = 'block';
                 toggleIcon.textContent = '▲';
                 
                 // 加载分组URL列表
                 const groupId = urlsContainer.closest('.group-card').dataset.groupId;
                 loadGroupURLs(groupId, index);
             } else {
                 urlsContainer.style.display = 'none';
                 toggleIcon.textContent = '▼';
             }
         }

        // 加载分组URL列表
        async function loadGroupURLs(groupId, index) {
            try {
                const response = await fetch('/api/ai-grouping/assignments?groupId=' + groupId);
                const result = await response.json();
                
                const urlsContainer = document.getElementById('group-urls-' + index);
                
                if (result.code === 200 && result.data.length > 0) {
                    urlsContainer.innerHTML = 
                        '<div class="urls-header">' +
                            '<h4>分组网址 (' + result.data.length + '个)</h4>' +
                        '</div>' +
                        '<div class="urls-list">' +
                            result.data.map(url => 
                                '<div class="url-item">' +
                                    '<div class="url-info">' +
                                        '<div class="url-title">' + (url.title || '无标题') + '</div>' +
                                        '<div class="url-link">' + url.url + '</div>' +
                                        '<div class="url-meta">' +
                                            '<span class="visit-count">访问 ' + url.visitCount + ' 次</span>' +
                                            '<span class="last-visit">最后访问: ' + formatDate(url.lastVisit) + '</span>' +
                                        '</div>' +
                                    '</div>' +
                                    '<div class="url-actions">' +
                                        '<a href="' + url.url + '" target="_blank" class="btn btn-sm">访问</a>' +
                                    '</div>' +
                                '</div>'
                            ).join('') +
                        '</div>';
                } else {
                    urlsContainer.innerHTML = '<div class="no-urls">该分组暂无网址</div>';
                }
            } catch (error) {
                console.error('加载分组URL失败：', error);
                const urlsContainer = document.getElementById('group-urls-' + index);
                urlsContainer.innerHTML = '<div class="error">加载失败：' + error.message + '</div>';
            }
        }

         // 切换测试分组展开/收起
         function toggleTestGroup(index) {
             const urlsContainer = document.getElementById('test-group-urls-' + index);
             const toggleIcon = document.querySelector(`#test-group-urls-${index}`).parentElement.querySelector('.toggle-icon');
             
             if (urlsContainer.style.display === 'none') {
                 urlsContainer.style.display = 'block';
                 toggleIcon.textContent = '▲';
             } else {
                 urlsContainer.style.display = 'none';
                 toggleIcon.textContent = '▼';
             }
         }

        // 加载测试分组URL列表
        function loadTestGroupURLs(group, index) {
            // 使用API返回的真实数据
            setTimeout(() => {
                const urlsContainer = document.getElementById('test-group-urls-' + index);
                
                // 使用API返回的真实sampleURLs数据
                const realURLs = group.sampleURLs || [];
                
                urlsContainer.innerHTML = 
                    '<div class="urls-header">' +
                        '<h4>分组网址 (' + realURLs.length + '个)</h4>' +
                    '</div>' +
                    '<div class="urls-list">' +
                        realURLs.map(url => 
                            '<div class="url-item">' +
                                '<div class="url-info">' +
                                    '<div class="url-title">' + extractTitleFromURL(url) + '</div>' +
                                    '<div class="url-link">' + url + '</div>' +
                                    '<div class="url-meta">' +
                                        '<span class="visit-count">真实URL</span>' +
                                        '<span class="last-visit">来自浏览历史</span>' +
                                    '</div>' +
                                '</div>' +
                                '<div class="url-actions">' +
                                    '<a href="' + url + '" target="_blank" class="btn btn-sm">访问</a>' +
                                '</div>' +
                            '</div>'
                        ).join('') +
                    '</div>';
            }, 500);
        }
        
        // 从URL提取标题
        function extractTitleFromURL(url) {
            try {
                const urlObj = new URL(url);
                const domain = urlObj.hostname.replace('www.', '');
                const path = urlObj.pathname;
                
                // 根据域名和路径生成有意义的标题
                if (domain.includes('github.com')) {
                    return 'GitHub - 代码托管平台';
                } else if (domain.includes('stackoverflow.com')) {
                    return 'Stack Overflow - 编程问答社区';
                } else if (domain.includes('baidu.com')) {
                    return '百度 - 搜索引擎';
                } else if (domain.includes('localhost') || domain.includes('127.0.0.1')) {
                    return '本地开发环境';
                } else if (domain.includes('weibo.com')) {
                    return '微博 - 社交媒体';
                } else if (domain.includes('taobao.com')) {
                    return '淘宝 - 电商平台';
                } else if (domain.includes('jd.com')) {
                    return '京东 - 电商平台';
                } else if (domain.includes('amazon.com')) {
                    return '亚马逊 - 电商平台';
                } else if (domain.includes('twitter.com')) {
                    return 'Twitter - 社交媒体';
                } else if (domain.includes('facebook.com')) {
                    return 'Facebook - 社交网络';
                } else if (domain.includes('instagram.com')) {
                    return 'Instagram - 图片社交';
                } else if (domain.includes('reddit.com')) {
                    return 'Reddit - 社区论坛';
                } else if (domain.includes('cnn.com')) {
                    return 'CNN - 国际新闻';
                } else if (domain.includes('bbc.com')) {
                    return 'BBC - 国际新闻';
                } else if (domain.includes('ctrip.com')) {
                    return '携程 - 旅游服务';
                } else if (domain.includes('npmjs.com')) {
                    return 'npm - 包管理器';
                } else if (domain.includes('kubernetes.io')) {
                    return 'Kubernetes - 容器编排';
                } else if (domain.includes('docker.com')) {
                    return 'Docker - 容器技术';
                } else if (domain.includes('ycombinator.com')) {
                    return 'Hacker News - 技术新闻';
                } else if (domain.includes('hao123.com')) {
                    return 'hao123 - 网址导航';
                } else if (domain.includes('sohu.com')) {
                    return '搜狐 - 新闻门户';
                } else if (domain.includes('sina.com.cn')) {
                    return '新浪 - 新闻门户';
                } else if (domain.includes('qq.com')) {
                    return '腾讯 - 综合门户';
                } else if (domain.includes('163.com')) {
                    return '网易 - 新闻门户';
                } else if (domain.includes('publicservices.hrss.tj.gov.cn')) {
                    return '天津人社 - 政府服务';
                } else {
                    // 默认生成标题
                    const domainParts = domain.split('.');
                    const siteName = domainParts[0].charAt(0).toUpperCase() + domainParts[0].slice(1);
                    return siteName + ' - 网站';
                }
            } catch (e) {
                return '网站链接';
            }
        }

        // 生成模拟URL数据
         function generateMockURLs(count, groupName) {
             const mockURLs = [];
             const domains = {
                 '高频访问': ['google.com', 'baidu.com', 'github.com', 'stackoverflow.com'],
                 '中频访问': ['amazon.com', 'taobao.com', 'jd.com', 'sina.com.cn'],
                 '低频访问': ['reddit.com', 'hackernews.com', 'medium.com', 'dev.to'],
                 '工作日访问': ['linkedin.com', 'slack.com', 'trello.com', 'asana.com'],
                 '周末访问': ['youtube.com', 'netflix.com', 'bilibili.com', 'douyin.com'],
                 '早晨访问': ['news.ycombinator.com', 'bbc.com', 'cnn.com', 'reuters.com'],
                 '下午访问': ['medium.com', 'dev.to', 'css-tricks.com', 'smashingmagazine.com'],
                 '晚上访问': ['youtube.com', 'twitch.tv', 'bilibili.com', 'douyin.com'],
                 '深夜访问': ['reddit.com', '4chan.org', '9gag.com', 'imgur.com']
             };
             
             const groupDomains = domains[groupName] || ['example.com', 'test.com', 'demo.com'];
             
             for (let i = 0; i < count; i++) {
                 const domain = groupDomains[i % groupDomains.length];
                 const path = i % 3 === 0 ? '/' : '/path' + (i + 1);
                 const url = 'https://' + domain + path;
                 
                 mockURLs.push({
                     url: url,
                     title: domain.charAt(0).toUpperCase() + domain.slice(1) + ' - 网站 ' + (i + 1),
                     visitCount: Math.floor(Math.random() * 20) + 1,
                     lastVisit: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toLocaleString('zh-CN')
                 });
             }
             
             return mockURLs;
         }

         // 格式化日期
         function formatDate(dateString) {
             if (!dateString) return '未知';
             const date = new Date(dateString);
             return date.toLocaleString('zh-CN');
         }

        // 显示消息
        function showMessage(message, type) {
            const messageDiv = document.createElement('div');
            messageDiv.className = type;
            messageDiv.textContent = message;
            
            const container = document.querySelector('.container');
            container.insertBefore(messageDiv, container.firstChild);
            
            setTimeout(() => {
                messageDiv.remove();
            }, 5000);
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            console.log('AI分组页面已加载');
        });
    </script>
</body>
</html>